﻿<%@ WebHandler Language="C#" Class="RBProductWorkingPrintHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using System.Web.SessionState;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using QRCoder;
using System.Drawing;

//Description: 热表分厂产品加工流水卡打印处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2022-01-19

public class RBProductWorkingPrintHandler : IHttpHandler, IRequiresSessionState
{
    RbContainerBusiness rbBusiness = new RbContainerBusiness();
    DataTable dtMain = new DataTable();//数据主表
    DataTable faContainerAttrDt = new DataTable();//父批次属性表
    DataTable dtDataPoint = new DataTable();//批次属性表
    DataTable dtStepInfo = new DataTable();//工步表
    DataTable dtStepInfoNotes = new DataTable();//工步备注表
    DataTable dtStepInfoCheckItem = new DataTable();//工步检测项表
    int pageHeight = 1000;//一页的高度
    int currHeight = 0;//页面当前高度
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request.Form["action"].ToString();
            switch (action)
            {
                case "GetPage"://热表批次打印
                    InitPage(context);
                    break;
                case "GetFollowPrint": //随件卡打印
                    GetFollowPrint(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "出错了：" + e.Message, Result = false }));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 初始化页面数据
    /// </summary>
    /// <param name="context"></param>
    public void InitPage(HttpContext context)
    {
        string strHtml = string.Empty;
        List<Dictionary<string, object>> printSession = (List<Dictionary<string, object>>)context.Session["PrintInfo"];
        context.Session.Remove("PrintInfo");
        if (printSession != null && printSession.Count > 0)
        {
            for (int i = 0; i < printSession.Count; i++)
            {
                DataSet dtset = rbBusiness.GetContainerPrintInfo(printSession[i]);
                if (dtset.Tables.Count == 0 || dtset.Tables["dtMain"].Rows.Count == 0)
                {
                    continue;
                }
                strHtml += i > 0 && !string.IsNullOrWhiteSpace(strHtml) ? GetPaging() : ""; //大于一条且不为空，则分页
                strHtml += GetPageHtml(dtset);
            }
        }
        else
        {
            string ContainerId = context.Request["ContainerId"];
            string WorkflowId = context.Request["WorkflowId"];
            if (string.IsNullOrEmpty(ContainerId) || string.IsNullOrEmpty(WorkflowId))
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "刷新无效，请关闭后重新打印", Result = false }));
                return;
            }
            Dictionary<string, object> printInfo = new Dictionary<string, object>();
            printInfo["ContainerId"] = ContainerId;
            printInfo["WorkflowId"] = WorkflowId;
            DataSet dtset = rbBusiness.GetContainerPrintInfo(printInfo);

            if (dtset.Tables.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未找到热表批次", Result = false }));
                return;
            }
            strHtml += GetPageHtml(dtset);
        }
        //strHtml += GetPageHtmlByTest();
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, ReturnData = strHtml }));
    }



    /// <summary>
    /// 获取页面html
    /// </summary>
    /// <param name="context"></param>
    public string GetPageHtml(DataSet ds)
    {
        dtMain = ds.Tables["dtMain"]; //数据主表
        DataRow drMain = dtMain.AsEnumerable().Where(p => !string.IsNullOrWhiteSpace(p["facontainerid"].ToString())).FirstOrDefault();//取父卡不为空的一条数据，原代码：dtMain.Rows[0]; //取第一条数据
        if (drMain == null)
        {
            drMain = dtMain.Rows[0];
        }
        faContainerAttrDt = ds.Tables["faContainerAttrDt"];//父批次属性表
        dtDataPoint = ds.Tables["dtDataPoint"];//批次属性表
        dtStepInfo = ds.Tables["dtStepInfo"];//工步表
        dtStepInfoNotes = ds.Tables["dtStepInfoNotes"];//工步备注表
        dtStepInfoCheckItem = ds.Tables["dtStepInfoCheckItem"];//工步检测项表
        string strHtml = "<div style='width:1005px;height:700px'>";
        if (dtStepInfo.Rows.Count > 0)
        {
            strHtml = "<div style='width:700px'>";
        }
        string charactertype = drMain["charactertype"].ToString().Trim();
        strHtml += string.Format("<div><label class='headTitle'>热表厂产品加工流水卡</label><label class='rightHeadTitle'>{0}</label></div>", charactertype == "重要件" || charactertype == "关键件" ? charactertype : "");
        strHtml += "<div><table class='productWorkingTable'";
        strHtml += string.Format("<tr><td colspan='3'><span>计划员</span></td><td colspan='3'>{0}</td></tr>", drMain["startname"].ToString()); //计划员
        strHtml += string.Format("<tr><td colspan='3'><span>生产订单号</span></td><td colspan='3'>{0}</td></tr>", drMain["mfgordername"].ToString());//生产订单号
        strHtml += string.Format("<tr><td colspan='3'><span>热表工艺规程编</span>号</td><td colspan='3'>{0}</td></tr>", drMain["process_no"].ToString() + (string.IsNullOrWhiteSpace(drMain["faprocess_no"].ToString()) || drMain["process_no"].ToString() == drMain["faprocess_no"].ToString() ? "" : "；" + drMain["faprocess_no"].ToString()));//热表工艺规程编号
        strHtml += string.Format("<tr><td colspan='3'>特殊过程确认、编号</td><td colspan='3'>{0}</td></tr>", drMain["isspotcheck"].ToString() != "1" ? "<div class='takeLine'></div>" : drMain["specialcoursespecreportno"].ToString());//特殊过程确认、编号
        strHtml += string.Format("<tr><td><span>热表加工批次</span></td><td colspan='2'>{0}</td><td><span>库存地点</td><td colspan='2'>{1}</td></tr>", drMain["rbtogetherflag"].ToString(), drMain["lgort"].ToString());//热表加工批次号，库存地点
        strHtml += string.Format("<tr><td>委托单位</td><td colspan='2'>{0}</td><td>开卡日期</td><td colspan='2'>{1}</td></tr>", string.IsNullOrWhiteSpace(drMain["fafactoryname"].ToString()) ? "<div class='takeLine'></div>" : drMain["fafactoryname"].ToString(), string.IsNullOrWhiteSpace(drMain["originalstartdate"].ToString()) ? "--" : drMain["originalstartdate"].ToString());//委托单位，加工日期
        strHtml += string.Format(" <tr><td style='width:80px;'><span>件</span>号</td><td style='width:140px'>{0}</td>", string.IsNullOrWhiteSpace(drMain["faproductname"].ToString()) ? "<div class='takeLine'></div>" : drMain["faproductname"].ToString()); //件号
        strHtml += string.Format("<td style='width:100px'><span>名</span>称</td><td style='width:140px'>{0}</td>", string.IsNullOrWhiteSpace(drMain["faproductdesc"].ToString()) ? "<div class='takeLine'></div>" : drMain["faproductdesc"].ToString());//名称
        strHtml += string.Format("<td style='width:100px'><span>型</span>别</td><td style='width:140px'>{0}</td></tr>", string.IsNullOrWhiteSpace(drMain["mfgbatch"].ToString().TrimEnd('|')) ? "<div class='takeLine'></div>" : drMain["mfgbatch"].ToString().TrimEnd('|'));//型别
        strHtml += string.Format("<tr><td><span>批</span>次</td><td>{0}</td>", drMain["FAContainertype"].ToString() == "7" ? drMain["FAContainerNo"].ToString() : drMain["FARealContainerNo"].ToString());//批次
        strHtml += string.Format("<td><span>数</span>量</td><td>{0}</td>", string.IsNullOrWhiteSpace(drMain["originalqty"].ToString()) ? "<div class='takeLine'></div>" : drMain["originalqty"].ToString());//数量
        strHtml += string.Format("<td>材料牌号</td><td>{0}</td></tr>", string.IsNullOrWhiteSpace(drMain["faMaterialtrademark"].ToString()) ? "<div class='takeLine'></div>" : drMain["faMaterialtrademark"].ToString());//材料牌号
        strHtml += string.Format(" <tr><td><span>工序</span>号</td><td>{0}</td>", (drMain["iskey"].ToString() == "1" ? "G" : "") + (string.IsNullOrWhiteSpace(drMain["faspecno"].ToString()) ? "<div class='takeLine'></div>" : drMain["faspecno"].ToString()));//工序号
        strHtml += string.Format("<td>工序内容</td><td>{0}</td>", string.IsNullOrWhiteSpace(drMain["faopdesc"].ToString()) ? "<div class='takeLine'></div>" : drMain["faopdesc"].ToString());//工序内容
        strHtml += string.Format("<td>材料规格</td><td>{0}</td></tr>", string.IsNullOrWhiteSpace(drMain["faMaterialSpecification"].ToString()) ? "<div class='takeLine'></div>" : drMain["faMaterialSpecification"].ToString());//材料规格   
        //属性填充      
        string attr = "<div class='takeLine'></div>";//默认横线
        if (faContainerAttrDt.Rows.Count == 0)
        {
            strHtml += string.Format("<tr><td><span>熔炉</span>号</td><td>{0}</td>", attr);//熔炉号
            strHtml += string.Format("<td>平行作业单号</td><td>{0}</td>", attr);//平行作业单号
            strHtml += string.Format("<td>平行作业工序</td><td>{0}</td></tr>", attr);//平行作业工序
            strHtml += string.Format("<td>代料单号</td><td>{0}</td>", attr);//代料单号
            strHtml += string.Format("<td>代料牌号</td><td>{0}</td>", attr);//代料牌号
            strHtml += string.Format("<td>代料规格</td><td>{0}</td></tr>", attr);//代料规格
            strHtml += string.Format("<tr><td colspan='6'><div style='height:200px;float:left;;text-align:justify; text-justify:inter-ideograph;word-break:break-all;'>备注：{0}</div></td></tr></table></div></div>", drMain["containercomments"].ToString());//备注
        }
        else
        {
            string faBatchcomments = faContainerAttrDt.Rows[0]["batchcomments"].ToString();
            var containerAttrDR = faContainerAttrDt.Select("userattributename='熔炉号母'").FirstOrDefault();
            if (containerAttrDR == null || string.IsNullOrWhiteSpace(containerAttrDR["attributevalue"].ToString()))
            {
                attr = "<div class='takeLine'></div>";
            }
            else
            {
                attr = containerAttrDR["attributevalue"].ToString();
                if (!string.IsNullOrWhiteSpace(faBatchcomments) && faBatchcomments.Split(',').Length > 1)
                {
                    attr = "见备注";
                }
            }
            strHtml += string.Format("<tr><td><span>熔炉</span>号</td><td>{0}</td>", attr);//熔炉号

            //containerAttrDR = faContainerAttrDt.Select("userattributename='平行作业单号'").FirstOrDefault();
            //attr = containerAttrDR == null || string.IsNullOrWhiteSpace(containerAttrDR["attributevalue"].ToString()) ? "--" : containerAttrDR["attributevalue"].ToString();
            //strHtml += string.Format("<td>平行作业单号</td><td>{0}</td>", attr);//平行作业单号

            //containerAttrDR = faContainerAttrDt.Select("userattributename='平行作业工序'").FirstOrDefault();
            //attr = containerAttrDR == null || string.IsNullOrWhiteSpace(containerAttrDR["attributevalue"].ToString()) ? "--" : containerAttrDR["attributevalue"].ToString();
            //strHtml += string.Format("<td>平行作业工序</td><td>{0}</td></tr>", attr);//平行作业工序

            //containerAttrDR = faContainerAttrDt.Select("userattributename='代料单号'").FirstOrDefault();
            //attr = containerAttrDR == null || string.IsNullOrWhiteSpace(containerAttrDR["attributevalue"].ToString()) ? "--" : containerAttrDR["attributevalue"].ToString();
            //strHtml += string.Format("<tr><td>代料单号</td><td>{0}</td>", attr);//代料单号

            //containerAttrDR = faContainerAttrDt.Select("userattributename='代料牌号'").FirstOrDefault();
            //attr = containerAttrDR == null || string.IsNullOrWhiteSpace(containerAttrDR["attributevalue"].ToString()) ? "--" : containerAttrDR["attributevalue"].ToString();
            //strHtml += string.Format("<td>代料牌号</td><td>{0}</td>", attr);//代料牌号

            //containerAttrDR = faContainerAttrDt.Select("userattributename='代料规格'").FirstOrDefault();
            //attr = containerAttrDR == null || string.IsNullOrWhiteSpace(containerAttrDR["attributevalue"].ToString()) ? "--" : containerAttrDR["attributevalue"].ToString();
            //strHtml += string.Format("<td>代料规格</td><td>{0}</td></tr>", attr);//代料规格

            string strRemark = string.Empty;//备注
            if (dtMain.Rows.Count > 1 || drMain["facontainertype"].ToString() == "7") //如果主表数据大于一条或者类型为单件单卡，拼接所有的委托单位，赋值给备注
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("containerNo");
                dt.Columns.Add("rongluhao");
                foreach (DataRow item in dtMain.Rows)
                {
                    DataRow dr = dt.NewRow();
                    dr["containerNo"] = item["facontainername"].ToString().Replace(item["orgfaproductname"].ToString() + "/", "");
                    var attrv = faContainerAttrDt.Select(string.Format("userattributename='熔炉号母' and parentid='{0}'", item["facontainerid"].ToString())).FirstOrDefault();
                    dr["rongluhao"] = attrv == null || string.IsNullOrWhiteSpace(attrv["attributevalue"].ToString()) ? "" : attrv["attributevalue"].ToString();
                    dt.Rows.Add(dr);
                }
                strRemark = GetNotes(dt);
            }
            if (!string.IsNullOrWhiteSpace(faBatchcomments) && faBatchcomments.Split(',').Length > 1)
            {
                strRemark += "熔炉号：";
                foreach (string item in faBatchcomments.Split(','))
                {
                    string[] strs = item.Split(':');
                    if (strs.Length > 0)
                    {
                        strRemark += strs[0] + ",";
                    }
                }
            }
            Tuple<string, string> attrs = GetAttrData("平行作业单号");
            strHtml += string.Format("<td>平行作业单号</td><td>{0}</td>", attrs.Item1);//平行作业单号
            strRemark += attrs.Item2;

            attrs = GetAttrData("平行作业工序");
            strHtml += string.Format("<td>平行作业工序</td><td>{0}</td></tr>", attrs.Item1);//平行作业工序
            strRemark += attrs.Item2;

            attrs = GetAttrData("代料单号");
            strHtml += string.Format("<td>代料单号</td><td>{0}</td>", attrs.Item1);//代料单号
            strRemark += attrs.Item2;

            attrs = GetAttrData("代料牌号");
            strHtml += string.Format("<td>代料牌号</td><td>{0}</td>", attrs.Item1);//代料牌号
            strRemark += attrs.Item2;

            attrs = GetAttrData("代料规格");
            strHtml += string.Format("<td>代料规格</td><td>{0}</td></tr>", attrs.Item1);//代料规格
            strRemark += attrs.Item2;

            //备注显示
            strRemark += drMain["containercomments"].ToString();//批次备注
            strRemark = strRemark.Trim(',');
            if (strRemark.Length > 1200)
            {
                strHtml += string.Format("<tr><td colspan='6'><div style='height:" + (dtStepInfo.Rows.Count > 0 ? "500px" : "200px") + ";float:left;text-align:justify; text-justify:inter-ideograph;word-break:break-all; font-size: 10px'>备注：{0}</div></td></tr></table></div>", strRemark);//备注
            }
            else
            {
                strHtml += string.Format("<tr><td colspan='6'><div style='height:" + (dtStepInfo.Rows.Count > 0 ? "500px" : "200px") + ";float:left;;text-align:justify; text-justify:inter-ideograph;word-break:break-all;'>备注：{0}</div></td></tr></table></div>", strRemark);//备注
            }
        }
        //条形码
        strHtml += string.Format("<div style='height:70px;'><div class=barCode style='float:Right'>*{0}*</div> <div style='clear:both'></div></div></div>", drMain["containerid"].ToString());
        strHtml += dtStepInfo.Rows.Count > 0 ? GetPaging() + GetProcedureTable() : "";//绑定工步列表
        strHtml += dtStepInfo.Rows.Count > 0 && dtStepInfoCheckItem.Rows.Count > 0 ? GetPaging() + GetStepInfoCheckItemTable() : "";//绑定工步检测项
        return strHtml;
    }
    /// <summary>
    /// 绑定工步数据
    /// </summary>
    /// <returns></returns>
    public string GetProcedureTable()
    {
        string strHtml = GetStepInfoTableTitle();//工步表头
        //循环工步表格，并填充值
        for (int i = 0; i < dtStepInfo.Rows.Count; i++)
        {
            if (string.IsNullOrWhiteSpace(dtStepInfo.Rows[i]["stepno"].ToString()) && string.IsNullOrWhiteSpace(dtStepInfo.Rows[i]["stepinfoname"].ToString()))//工步号和工步名为空，则不打印
            {
                continue;
            }
            Tuple<string, int> resData = GetStepInfoTableContent(dtStepInfo.Rows[i]);//工步内容和内容高度
            if (currHeight + resData.Item2 > pageHeight)//如果加上这一行大于总高度,分页显示
            {
                strHtml += "</table>" + GetPaging();//分页
                strHtml += GetStepInfoTableTitle();//工步表头
            }
            strHtml += resData.Item1;//工步内容
            currHeight += resData.Item2;//累加行高度
        }
        //如果最后一页的高度小于一页的高度，追加空白行
        if (currHeight < pageHeight)
        {
            for (currHeight = currHeight + 30; currHeight < pageHeight; currHeight = currHeight + 30)
            {
                strHtml += @"<tr style='height:30px'><td></td><td></td><td></td><td></td><td></td>
                             <td></td><td></td><td></td><td></td><td></td><td></td></tr>";
            }
        }
        strHtml += "</table>";
        return strHtml;
    }

    /// <summary>
    /// 获取工步表头
    /// </summary>
    /// <returns></returns>
    private string GetStepInfoTableTitle()
    {
        currHeight = 60;//重置高度
        return @"<table class='stepInfoTable'><tr style='height:40px'><td rowspan='2' style='width:50px;'>工步号</td><td rowspan='2' style='width:150px'>工步名称</td><td rowspan='2' style='width:30px'>数量</td>
<td colspan='4'>检验结果</td><td rowspan='2' style='width:100px'>加工日期</td><td rowspan='2' style='width:80px'>工人</td>
<td rowspan='2' style='width:80px'>检验印</td><td rowspan='2' style='width:100px'>备注</td></tr>
                    <tr><td style='width:30px'>合格</td><td style='width:30px'>报废</td><td style='width:30px'>超差</td><td style='width:30px'>返修</td></tr>";
    }
    /// <summary>
    /// 获取工步表格内容
    /// </summary>
    /// <returns></returns>
    private Tuple<string, int> GetStepInfoTableContent(DataRow dr)
    {
        int h = 30;
        string notes = string.Empty;//备注
        List<string> noteList = new List<string>();
        DataRow[] drs = dtStepInfoNotes.Select("stepinfoid='" + dr["stepinfoid"].ToString() + "' and workerid = '" + dr["workerid"].ToString() + "' and checkerid = '" + dr["checkerid"].ToString() + "'");
        foreach (DataRow item in drs)
        {
            noteList.Add(item["notes"].ToString());
            noteList.Add(item["checknote"].ToString());
        }
        noteList = noteList.Where((x, i) => noteList.FindIndex(z => z == x) == i).ToList();//去重
        noteList.ForEach(p => notes += p + ",");
        notes = notes.Trim(',');
        int notebytes = System.Text.Encoding.Default.GetByteCount(notes);//得到备注的字节长度
        int noteCount = (notebytes / 15) + 1;//一行显示14个字节，除去15并加1得到备注占据多少行
        if (noteCount > 1)
        {
            h += 10 * (noteCount - 1);//多一行高度增加10
        }
        string reportDate = dr["reportdate"].ToString();
        if (!string.IsNullOrWhiteSpace(reportDate))
        {
            reportDate = DateTime.Parse(reportDate).ToString("yyyy-MM-dd");
        }
        string strContent = "<tr style='height:" + h + "px'>";
        strContent += "<td>" + dr["stepno"].ToString() + "</td>";//工步号
        strContent += "<td>" + dr["stepinfoname"].ToString() + "</td>";//工步名称
        strContent += "<td>" + GetBlankNum(dr["checkqty"].ToString()) + "</td>";//数量（检验数量）
        string acceptanceqty = GetBlankNum(dr["acceptanceqty2"].ToString());
        strContent += "<td>" + (string.IsNullOrWhiteSpace(acceptanceqty) ? GetBlankNum(dr["acceptanceqty"].ToString()) : acceptanceqty) + "</td>";//合格
        strContent += "<td>" + GetBlankNum(dr["lossqty"].ToString()) + "</td>";//报废
        strContent += "<td>" + GetBlankNum(dr["defectqty"].ToString()) + "</td>";//超差
        strContent += "<td>" + GetBlankNum(dr["reworkqty"].ToString()) + "</td>";//返修
        strContent += "<td>" + reportDate + "</td>";//加工日期
        strContent += "<td>" + dr["workername"].ToString() + "</td>";//工人
        strContent += "<td>" + dr["checkername"].ToString() + "</td>";//检验印
        strContent += "<td>" + notes + "</td></tr>";//备注
        return new Tuple<string, int>(strContent, h);
    }

    /// <summary>
    /// 获取工步检测项表格
    /// </summary>
    /// <returns></returns>
    private string GetStepInfoCheckItemTable()
    {
        string strHtml = GetStepInfoCheckItemTableTitle();//检测项表头
        DataTable dtStepInfoCI = dtStepInfoCheckItem.DefaultView.ToTable(true, new string[1] { "stepinfoid" });//获取有检测项的工步并去重
        //循环工步表格，并填充值
        for (int i = 0; i < dtStepInfoCI.Rows.Count; i++)
        {
            Tuple<string, int> resData = GetStepInfoCheckItemTableContent(dtStepInfoCI.Rows[i]["stepinfoid"].ToString());//工步检测项内容和内容高度
            if (currHeight + resData.Item2 > pageHeight)//如果加上这一行大于总高度,分页显示
            {
                strHtml += "</table>" + GetPaging();//分页
                strHtml += GetStepInfoCheckItemTableTitle();//检测项表头
            }
            strHtml += resData.Item1;//工步内容
            currHeight += resData.Item2;//累加行高度
        }
        strHtml += "</table>";
        return strHtml;
    }

    /// <summary>
    /// 获取检测项表头
    /// </summary>
    /// <returns></returns>
    private string GetStepInfoCheckItemTableTitle()
    {
        currHeight = 60;//重置高度
        return @"<table class='stepInfoTable'><tr style='height:40px'><td style='width:50px;'>工步号</td><td style='width:100px'>工步名称</td><td colspan='2' style='width:150px'>检验内容</td><td style='width:150px'>图纸要求</td>
<td style='width:100px'>实际值</td><td style='width:50px'>工人</td><td style='width:50px'>检验员</td></tr>";
    }

    /// <summary>
    /// 获取检测项内容
    /// </summary>
    /// <param name="dr"></param>
    /// <returns></returns>
    private Tuple<string, int> GetStepInfoCheckItemTableContent(string stepInfoId)
    {
        int rowHeight = 0;
        int h = 0;
        string strContent = "";//html内容
        string workerName = "";//工人
        string checkerName = "";//检验员
        DataRow[] drCheckItems = dtStepInfoCheckItem.Select("stepinfoid='" + stepInfoId + "'");
        for (int i = 0; i < drCheckItems.Length; i++)
        {
            h = 30;
            DataRow item = drCheckItems[i];
            string checkpointnote = item["checkpointnotedis_b"].ToString().Trim();//检测内容
            if (string.IsNullOrWhiteSpace(checkpointnote))
            {
                checkpointnote = item["checkpointnote"].ToString().Trim();
            }
            string drawingrequire = item["drawingrequiredis_b"].ToString().Trim();//图纸要求
            if (string.IsNullOrWhiteSpace(drawingrequire))
            {
                drawingrequire = item["drawingrequire"].ToString().Trim();
            }
            int notebytes1 = System.Text.Encoding.Default.GetByteCount(checkpointnote);//得到要求值的字节长度
            //实际值
            string checkpointresultnote = string.IsNullOrWhiteSpace(item["checkpointresultnotedis"].ToString()) ? string.IsNullOrWhiteSpace(item["checkpointresultnote"].ToString()) ? item["checkpointresultnotedis_b"].ToString() : item["checkpointresultnote"].ToString() : item["checkpointresultnotedis"].ToString();
            if (string.IsNullOrWhiteSpace(checkpointresultnote))
            {
                checkpointresultnote = string.IsNullOrWhiteSpace(item["workcheckpointresultnotedis"].ToString()) ? string.IsNullOrWhiteSpace(item["workcheckpointresultnote"].ToString()) ? item["workcheckpointresultnotedis_b"].ToString() : item["workcheckpointresultnote"].ToString() : item["workcheckpointresultnotedis"].ToString();
            }
            int notebytes2 = System.Text.Encoding.Default.GetByteCount(checkpointresultnote);//得到实际值的字节长度
            if (checkpointresultnote.Contains("data:image/png;base64"))//如果实测值是base64位，无法计算内容的长度，则按照要求值来计算
            {
                notebytes2 = 0;
            }
            int notebytes = notebytes1 > notebytes2 ? notebytes1 : notebytes2;//去两个值的最大
            int noteCount = (notebytes / 29) + 1;//一行显示28个字节，除去29并加1得到备注占据多少行
            if (noteCount > 1)
            {
                h += 10 * (noteCount - 1);//多一行高度增加10
            }
            strContent += "<tr style='height:" + h + "px'>";
            if (i == 0) //第一行做跨行处理
            {
                strContent += "<td rowspan = '" + drCheckItems.Length + "'>" + item["stepno"].ToString() + "</td>";//工步号
                strContent += "<td rowspan = '" + drCheckItems.Length + "'>" + item["stepinfoname"].ToString() + "</td>";//工步名称
            }
            strContent += "<td><div style='text-align:center;'>" + (i + 1) + "</div></td>";//序号
            strContent += "<td><div style='float:left;text-align:justify; text-justify:inter-ideograph;word-break:break-all;'>" + checkpointnote + "</div></td>";//要求值
            strContent += "<td>" + drawingrequire + "</td>";//图纸要求
            strContent += "<td>" + checkpointresultnote + "</td>";//实际值
            if (i == 0) //第一行做跨行处理
            {
                strContent += "<td rowspan = '" + drCheckItems.Length + "'>{0}</td>";//工人
                strContent += "<td rowspan = '" + drCheckItems.Length + "'{2}>{1}</td>";//检验员
            }
            strContent += "</tr>";
            if (!string.IsNullOrWhiteSpace(item["workername"].ToString()))
            {
                if (!workerName.Contains(item["workername"].ToString().Trim()))
                {
                    workerName += item["workername"].ToString() + ",";
                }
            }
            if (!string.IsNullOrWhiteSpace(item["checkername"].ToString()))
            {
                if (!checkerName.Contains(item["checkername"].ToString().Trim()))
                {
                    checkerName += item["checkername"].ToString() + ",";
                }
            }
            rowHeight += h;
        }
        h = 30;
        workerName = workerName.Trim(',');
        checkerName = checkerName.Trim(',');
        int notebytes3 = System.Text.Encoding.Default.GetByteCount(workerName);//得到工人的字节长度
        int notebytes4 = System.Text.Encoding.Default.GetByteCount(checkerName);//得到检验员的字节长度
        int notebytess = notebytes3 > notebytes4 ? notebytes3 : notebytes4;//去两个值的最大
        int noteCount1 = (notebytess / 13) + 1;//一行显示12个字节，除去13并加1得到备注占据多少行
        if (noteCount1 > 1)
        {
            h += 10 * (noteCount1 - 1);//多一行高度增加10
        }
        strContent = rowHeight >= h ? string.Format(strContent, workerName, checkerName, "") : string.Format(strContent, workerName, checkerName, "style='height:" + h + "px'");
        return new Tuple<string, int>(strContent, rowHeight > h ? rowHeight : h);
    }

    /// <summary>
    /// 获取字符串数字，如果为0或者空，返回空字符
    /// </summary>
    /// <param name="num"></param>
    /// <returns></returns>
    private string GetBlankNum(string num)
    {
        if (!string.IsNullOrWhiteSpace(num))
        {
            if (num.Trim() == "0")
            {
                return "";
            }
            return num;
        }
        return "";
    }
    /// <summary>
    /// 获取批次属性数据
    /// </summary>
    /// <param name="attrName"></param>
    /// <returns></returns>
    private Tuple<string, string> GetAttrData(string attrName)
    {
        string attr = "<div class='takeLine'></div>", remark = "";
        DataRow[] containerAttrDRs = faContainerAttrDt.Select(string.Format("userattributename='{0}'", attrName));
        foreach (DataRow item in containerAttrDRs)
        {
            if (!string.IsNullOrWhiteSpace(item["attributevalue"].ToString()))
            {
                remark += item["attributevalue"].ToString() + ",";
            }
        }
        remark = remark.Trim(',');
        if (!string.IsNullOrWhiteSpace(remark))
        {
            if (remark.Contains(","))
            {
                attr = "见备注";
                remark = attrName + "：" + remark;
            }
            else
            {
                attr = remark;
                remark = "";
            }
        }
        return new Tuple<string, string>(attr, remark);
    }

    /// <summary>
    /// 获取分页
    /// </summary>
    /// <returns></returns>
    private string GetPaging()
    {
        return "<div class='paging'></div>";
    }

    /// <summary>
    /// 获取备注
    /// </summary>
    /// <param name="dtMain"></param>
    /// <returns></returns>
    private string GetNotes(DataTable dt)
    {
        string notes = "";
        while (dt.Rows.Count > 0)
        {
            DataRow dr = dt.Rows[0];
            notes += "批次号:";
            string rlh = dr["rongluhao"].ToString();
            DataRow[] arr = dt.Select(string.Format("rongluhao='{0}'", rlh));
            arr = arr.AsEnumerable().OrderBy(p => p["containerNo"].ToString()).ToArray();
            foreach (DataRow item in arr)
            {
                notes += item["containerNo"].ToString() + ",";
                dt.Rows.Remove(item);
            }
            notes = notes.TrimEnd(',');
            notes += ";熔炉号:" + rlh;
            dt.AcceptChanges();
        }
        return notes;
    }

    /// <summary>
    /// 随件卡打印
    /// </summary>
    /// <param name="context"></param>
    private void GetFollowPrint(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Message = "获取成功", Result = true, ReturnData = "" };
        string formID = context.Request["formID"];
        string formData = context.Request["formData"];
        if (string.IsNullOrEmpty(formID) || string.IsNullOrEmpty(formData))
        {
            result.Message = "刷新无效，请关闭后重新打印"; result.Result = false;
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        switch ((PrintFormEm)int.Parse(formID))
        {
            case PrintFormEm.转工:
                result.ReturnData = GetShipContainerPrintHtml(formData);
                break;
            case PrintFormEm.无订单:
                result.ReturnData = GetOrderContainerPrintHtml(formData);
                break;
            default:
                result.Message = "未知功能打印，请查看"; result.Result = false;
                break;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取转工随件卡打印数据
    /// </summary>
    /// <param name="formData"></param>
    /// <returns></returns>
    private string GetShipContainerPrintHtml(string formData)
    {
        StringBuilder strHtml = new StringBuilder();
        List<Dictionary<string, string>> dataList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(formData);
        for (int i = 0; i < dataList.Count; i++)
        {
            DataTable dtShip = GetShipContainerPrintData(dataList[i]);
            for (int s = 0; s < dtShip.Rows.Count; s++)
            {
                DataRow drShip = dtShip.Rows[s];
                strHtml.AppendLine(GetFollowPritHtml(drShip));
                if (!(i == dataList.Count - 1 && s == dtShip.Rows.Count - 1))
                {
                    strHtml.AppendLine(GetPaging());//分页
                }
            }
        }
        return strHtml.ToString();
    }

    /// <summary>
    /// 获取采购订单随件卡打印数据
    /// </summary>
    /// <param name="formData"></param>
    /// <returns></returns>
    private string GetOrderContainerPrintHtml(string formData)
    {
        StringBuilder strHtml = new StringBuilder();
        List<Dictionary<string, string>> dataList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(formData);
        for (int i = 0; i < dataList.Count; i++)
        {
            DataTable dtOrder = GetOrderContainerPrintData(dataList[i]);
            for (int s = 0; s < dtOrder.Rows.Count; s++)
            {
                DataRow dr = dtOrder.Rows[s];
                strHtml.AppendLine(GetFollowPritHtml(dr));
                if (!(i == dataList.Count - 1 && s == dtOrder.Rows.Count - 1))
                {
                    strHtml.AppendLine(GetPaging());//分页
                }
            }
        }
        return strHtml.ToString();
    }

    /// <summary>
    /// 获取随件打印html
    /// </summary>
    /// <param name="dr"></param>
    /// <returns></returns>
    private string GetFollowPritHtml(DataRow dr)
    {
        StringBuilder strHtml = new StringBuilder();
        strHtml.AppendLine("<table class='productWorkingTable'>");
        strHtml.AppendLine("<tr><td colspan='4'>热表厂产品状态标识</td></tr>");
        strHtml.AppendFormat("<tr><td style='width:100px'>主制分厂</td><td>{0}</td>", dr["factoryname"].ToString());
        strHtml.AppendFormat("<td rowspan='3' colspan='2'><img src='data:image/Jpeg;base64,{0}'></td></tr>", CreateQRCodeImg(string.Format("{0}/{1}/{2}-{3}", dr["mfgordername"].ToString(), dr["facontainername"].ToString(), dr["specno"].ToString(), dr["opdesc"].ToString())));//批次ID二维码显示
        strHtml.AppendFormat("<tr><td>主批次号</td><td>{0}</td></tr>", dr["facontainername"].ToString());
        strHtml.AppendFormat("<tr><td>数量</td><td>{0}</td></tr>", dr["qty"].ToString());

        strHtml.AppendFormat("<tr><td>工序号</td><td>{0}</td>", dr["specno"].ToString());
        strHtml.AppendLine("<td style='width:100px'><input type='checkbox' class='checkB' /><label>待加工</label></td><td style='width:100px'><input type='checkbox' class='checkB' /><label>加工中</label></td></tr>");
        strHtml.AppendFormat("<tr><td>工序名称</td><td>{0}</td>", dr["opdesc"].ToString());
        strHtml.AppendLine("<td style='width:100px'><input type='checkbox' class='checkB' /><label>待检验</label></td><td style='width:100px'><input type='checkbox' class='checkB' /><label>已完成</label></td></tr>");
        strHtml.AppendFormat("<tr><td>备注</td><td colspan='3'>{0}</td></tr></table>", dr["notes"].ToString());
        return strHtml.ToString();
    }

    /// <summary>
    /// 获取转工批次随件卡打印数据
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    private DataTable GetShipContainerPrintData(Dictionary<string, string> param)
    {
        string sql = string.Format(@"SELECT cci.mfgordername,cci.containername facontainername,f.factoryname,cci.qty,s.specno,s.opdesc,csa.notes
                        FROM containershiprecord csr
                        LEFT JOIN containercurrentinfo cci ON cci.containerid = csr.containerid 
                        LEFT JOIN factory f ON f.factoryid = cci.originalfactoryid
                        LEFT JOIN containershiprecordstep csrs ON csrs.containershiprecordid = csr.containershiprecordid
                        LEFT JOIN workflowstep ws ON ws.workflowstepid = csrs.workflowstepid
                        LEFT JOIN containerstepattribute csa ON csa.containerid = cci.containerid AND csa.workflowstepid = ws.workflowstepid
                        LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                        left JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                        WHERE csr.containershiprecordid = '{0}' AND csr.containerid = '{1}'", param["ContainerShipRecordID"], param["ContainerID"]);
        return DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(sql);
    }

    /// <summary>
    /// 获取采购订单批次随件卡打印数据
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    private DataTable GetOrderContainerPrintData(Dictionary<string, string> param)
    {
        string sql = string.Format(@"SELECT cci.mfgordername,cci.containername,u1.attributevalue factoryname,cci.productname || '/' || u2.attributevalue facontainername,cci.qty,s.specno,s.opdesc,csa.notes
                        FROM containercurrentinfo cci 
                        LEFT JOIN userattribute u1 ON u1.parentid = cci.containerid AND u1.userattributename = '委托单位'
                        LEFT JOIN userattribute u2 ON u2.parentid = cci.containerid AND u2.userattributename = '委托批次'
                        LEFT JOIN workflowstep ws ON ws.workflowstepid = cci.workflowstepid
                        LEFT JOIN containerstepattribute csa ON csa.containerid = cci.containerid AND csa.workflowstepid = ws.workflowstepid
                        LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                        LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                        WHERE cci.containerid = '{0}'", param["containerID"]);
        return DatabaseAccess.DBUtility.DatabaseHelper.Query_ReturnDatTable(sql);
    }

    /// <summary>
    /// 生成二维码（base64）
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    protected string CreateQRCodeImg(string str)
    {
        QRCodeGenerator qrGenerator = new QRCodeGenerator();

        QRCodeData qrCodeData = qrGenerator.CreateQrCode(str, QRCodeGenerator.ECCLevel.L);
        QRCode qrcode = new QRCode(qrCodeData);

        Bitmap qrCodeImage = qrcode.GetGraphic(6, Color.Black, Color.White, null, 5, 1, false);
        MemoryStream ms = new MemoryStream();
        qrCodeImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

        return Convert.ToBase64String(ms.ToArray());
    }

    private enum PrintFormEm
    {
        转工 = 1,
        无订单 = 2
    }
}